const config = require('../config/index.js')
const ObjectId = require('mongodb').ObjectId
const MongoClient = require('mongodb').MongoClient
const Client = new MongoClient(config.mongodbUrl)

let num = 0
let dbInstance = null
let model = {
 cood:200,
 result:{}
}
/**
 * 获取数据库实例
 * @param {*} dbName 数据库名称
 * @param {*} collectionName 集合名称
 * @returns
 */

async function getDbInstance() {
	if (!dbInstance) {
		num++
		await Client.connect()
		dbInstance = Client
	}
	return dbInstance
}

/**
 * 数据库操作
 * @param {*} dbName 数据库名称
 * @param {*} collectionName 集合名称
 * @returns
 */

async function Db(dbName) {
	const client = await getDbInstance()
 console.log('MongoDB 连接 connecting:')
 const db = client.db(dbName)
	async function find(collectionName, json) {
		/*数据库查询*/
  let r = await db.collection(collectionName).find(json).toArray()
  if (r.length > 0) {
   model.result = r
  } else {
   model.cood = 500
   model.result = "数据查询失败"
  }
		return model
	}
	async function findOne(collectionName, json) {
		/*数据库查询*/
  let r = await db.collection(collectionName).find(json).toArray()
  if (r.length > 0) {
   model.result = r[0]
  } else {
   model.cood = 500
   model.result = "数据查询失败"
  }
		return model
	}

	async function update(collectionName, json1, json2) {
		/*单条数据库更新*/
  let r = await db.collection(collectionName).updateOne( json1, { $set: json2 })
  if (r.length > 0) {
   model.result = true
  } else {
   model.cood = 500
   model.result = false
  }
		return model
	}

	async function insert(collectionName, json) {
		/*数据库添加*/
		let res = await db.collection(collectionName).insertOne(json)
  if (res.acknowledged ) {
   model.result = res
  } else {
   model.cood = 500
   model.result = "数据数据新增失败"
  }
		return model
	}
	async function remove(collectionName, json) {
		/*数据库删除*/
		let res = await db.collection(collectionName).removeOne(json)
  if (res.acknowledged ) {
   model.result = res
  } else {
   model.cood = 500
   model.result = "数据数据新增失败"
  }
		return model
	}

	function getObjectId(id) {
		/*mongodb里面查询 _id 把字符串转换成对象*/
		return new ObjectId(id)
	}

	return {
		db,num,find,update,findOne,
  insert,remove,getObjectId
	}
}

module.exports = {DB:Db}
